package com.skt.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.skt.domain.DTO.request.MerchantCostumeCreateRequest;
import com.skt.domain.DTO.request.MerchantCostumeUpdateRequest;
import com.skt.domain.VO.MerchantBusinessStatisticsVO;
import com.skt.domain.VO.MerchantCostumeVO;
import com.skt.domain.VO.MerchantOrderVO;
import com.skt.service.MerchantService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;

@RestController
@RequiredArgsConstructor
@RequestMapping("/merchant/costumes")
@Tag(name = "商家后台接口")
public class MerchantController {

    private final MerchantService merchantService;

    @Operation(summary = "商家发布新服装")
    @ApiResponses({
            @ApiResponse(
                    responseCode = "201",
                    description = "发布成功",
                    // 接口成功返回的数据结构是 MerchantCostumeVO 类，用于自动生成 API 文档中的响应示例和字段说明。
                    content = @Content(schema = @Schema(implementation = MerchantCostumeVO.class))
            ),
            @ApiResponse(responseCode = "400", description = "请求参数无效"),
            @ApiResponse(responseCode = "403", description = "无权限（非商家或账号被禁用）"),
            @ApiResponse(responseCode = "409", description = "服装已存在（重复发布）")
    })
    @PostMapping()
    public ResponseEntity<MerchantCostumeVO> publishCostume(
            @Valid @RequestBody MerchantCostumeCreateRequest request) {
        MerchantCostumeVO result = merchantService.publishCostume(request);
        // 创建资源成功，返回 201 状态码和创建后的数据。
        return ResponseEntity.status(HttpStatus.CREATED).body(result);
    }


    @Operation(summary = "商家更新服装信息")
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "更新成功",
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = MerchantCostumeVO.class)
                    )
            ),
            @ApiResponse(responseCode = "400", description = "请求参数无效"),
            @ApiResponse(responseCode = "403", description = "无权限（非商家、账号被禁用或无权操作该服装）"),
            @ApiResponse(responseCode = "404", description = "服装不存在"),
            @ApiResponse(responseCode = "409", description = "服装信息重复（名称+类别+尺码+颜色已存在）")
    })
    @PutMapping("/{id}")
    public ResponseEntity<MerchantCostumeVO> updateCostume(
            @PathVariable Long id,
            @Valid @RequestBody MerchantCostumeUpdateRequest request) {
        MerchantCostumeVO result = merchantService.updateCostume(id, request);
        return ResponseEntity.ok(result);
    }


    @Operation(summary = "下架服装（仅修改状态为下架）")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "下架成功",
                    content = @Content(schema = @Schema(implementation = MerchantCostumeVO.class))),
            @ApiResponse(responseCode = "403", description = "无权限操作该服装"),
            @ApiResponse(responseCode = "404", description = "服装不存在"),
            @ApiResponse(responseCode = "409", description = "服装正在租借中，无法下架（若启用业务校验）")
    })
    @PutMapping("/{id}/status")
    public ResponseEntity<MerchantCostumeVO> offlineCostume(@PathVariable Long id) {
        MerchantCostumeVO result = merchantService.offlineCostume(id);
        return ResponseEntity.ok(result);
    }


    @Operation(summary = "查询商家自己的服装列表（分页）")
    @ApiResponses({
            @ApiResponse(
                    responseCode = "200",
                    description = "查询成功",
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = IPage.class) // 注意：实际 VO 在 records 中
                    )
            ),
            @ApiResponse(responseCode = "403", description = "无权限（非商家或账号被禁用）")
    })
    @GetMapping
    public IPage<MerchantCostumeVO> listCostumesByMerchant(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        return merchantService.listCostumesByMerchant(pageNum, pageSize);
    }


    @Operation(summary = "查询商家自己的订单列表（分页）")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "403", description = "无操作权限")
    })
    @GetMapping("/orders")
    public IPage<MerchantOrderVO> listOrdersByMerchant(
            @Parameter(description = "页码（从1开始）", example = "1")
            @RequestParam(defaultValue = "1") Integer pageNum,

            @Parameter(description = "每页数量（默认20，最大100）", example = "20")
            @RequestParam(defaultValue = "20") Integer pageSize) {
        return merchantService.listOrdersByMerchant(pageNum, pageSize);
    }


    @Operation(
            summary = "确认发货",
            description = "商家对状态为“待发货”的订单执行发货操作。该接口幂等：重复请求不会产生副作用。"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "204", description = "发货成功，无返回内容"),
            @ApiResponse(responseCode = "400", description = "订单ID无效（如非正整数）"),
            @ApiResponse(responseCode = "403", description = "当前用户未认证、非商家，或无权操作该订单"),
            @ApiResponse(responseCode = "404", description = "订单不存在"),
            @ApiResponse(responseCode = "409", description = "订单当前状态不允许发货（例如已发货、已取消等）")
    })
    @PutMapping("/orders/{id}/ship")
    public ResponseEntity<Void> shipOrder(
            // @Parameter 用于生成 API 文档（比如 Swagger UI 页面）。
            @Parameter(
                    description = "订单ID，必须为大于0的整数",
                    required = true,
                    example = "1001"
            )
            // @PathVariable 表示该参数的值来自 URL 路径中的变量。
            @PathVariable
            // @Min(value = 1) 对参数进行数据校验，确保其值 ≥ 1。
            @Min(value = 1, message = "订单ID必须为正整数")
            Long id) {
        merchantService.shipOrder(id);
        // 表示返回一个 HTTP 204 状态码，表示请求成功但无响应内容。
        return ResponseEntity.noContent().build();
    }


    @Operation(
            summary = "确认归还完成",
            description = "商家确认已收到用户退回的服装，将订单状态更新为“已归还”。" +
                    "该操作幂等：重复调用不会产生副作用，也不会重复触发库存回补。"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "204", description = "确认成功，无返回内容"),
            @ApiResponse(responseCode = "400", description = "订单ID无效（如非正整数）"),
            @ApiResponse(responseCode = "403", description = "未认证、非商家，或无权操作该订单"),
            @ApiResponse(responseCode = "404", description = "订单不存在"),
            @ApiResponse(responseCode = "409", description = "订单状态不允许确认归还（如未退货、已归还、已取消等）")
    })
    @PutMapping("/orders/{id}/return/received")
    public ResponseEntity<Void> confirmReturnReceived(
            @Parameter(description = "订单ID，必须为大于0的整数", required = true, example = "1002")
            @PathVariable
            @Min(value = 1, message = "订单ID必须为正整数")
            Long id) {
        merchantService.confirmReturnCompleted(id);
        return ResponseEntity.noContent().build();
    }


    @Operation(summary = "（可选）查看商家经营统计")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功",
                    content = @Content(schema = @Schema(implementation = MerchantBusinessStatisticsVO.class))),
            @ApiResponse(responseCode = "400", description = "时间参数错误"),
            @ApiResponse(responseCode = "403", description = "无操作权限")
    })
    @GetMapping("/statistics")
    public MerchantBusinessStatisticsVO getBusinessStatistics(
            @Parameter(description = "统计开始时间，格式：yyyy-MM-dd HH:mm:ss", example = "2024-01-01 00:00:00")
            @RequestParam(required = false) String startTime,

            @Parameter(description = "统计结束时间，格式：yyyy-MM-dd HH:mm:ss", example = "2024-01-31 23:59:59")
            @RequestParam(required = false) String endTime) {
        return merchantService.getBusinessStatistics(startTime, endTime);
    }
}